<template>
  <div ref="tabbar" class="tab-bar">
    <nav>
      <template
        v-for="(item, index) in tabList"
      >
        <a
          v-if="!item.path"
          :key="index"
          href="javascript:;"
          :class="{active: activeIndex === index}"
          @click="tabChange(index, item, $event)"
        >{{ item.title }}</a>
        <router-link
          v-else
          :key="index"
          :to="item.path"
          :class="{active: activeIndex === index}"
          @click.native="tabChange(index, $event)"
        >
          {{ item.title }}
        </router-link>
      </template>
    </nav>
  </div>
</template>

<script>
export default {
  name: 'TabBar',
  props: {
    tabList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      activeIndex: 0
    }
  },
  watch: {
    tabList () {
      this.activeIndex = 0
    }
  },
  methods: {
    tabChange (index, item, e) {
      this.activeIndex = index
      this.scrollAnimate(e.target)
      this.$emit('change', item)
    },
    scrollAnimate (item) {
      const tabbar = this.$refs.tabbar
      const offsetLeft = item.offsetLeft
      const centerLeft = offsetLeft - tabbar.clientWidth / 2 + item.clientWidth / 2
      tabbar.scrollTo(centerLeft, 0)
    }
  }
}
</script>

<style lang="scss" scoped>
.tab-bar {
  width: 100%;
  height: 92px;
  overflow: auto;
  line-height: 92px;
  background: #ffff;
  transition: all .5s ease;
  @include border1px(bottom, #E2E2E2);
  nav {
    @include flex(row, space-between, center);
    a {
      padding: 0 10px;
      flex-shrink: 0;
      position: relative;
      color: #4A4A4A;
      font-size: 28px;
      &.active {
        color: $base-color;
        &::after {
          content: '';
          display: block;
          height: 2px;
          width: 40px;
          background: $base-color;
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
        }
      }
    }
  }
}
</style>
